package com.love_weinuo.zxing.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout;
import com.google.zxing.Result;
import com.love_weinuo.R;
import com.love_weinuo.ui.BaseActivity;
import com.love_weinuo.util.HTTPAPI;
import com.love_weinuo.util.LogUtil;
import com.love_weinuo.util.SpUtils;
import com.love_weinuo.util.ToastUtil;
import com.love_weinuo.zxing.camera.CameraManager;
import com.love_weinuo.zxing.decode.DecodeThread;
import com.love_weinuo.zxing.utils.BeepManager;
import com.love_weinuo.zxing.utils.CaptureActivityHandler;
import com.love_weinuo.zxing.utils.InactivityTimer;
import com.lzy.okgo.callback.StringCallback;
import okhttp3.Call;
import okhttp3.Response;
/**
 * This activity opens the camera and does the actual scanning on a background
 * thread. It draws a viewfinder to help the user place the barcode correctly,
 * shows feedback as the image processing is happening, and then overlays the
 * results when a scan is successful.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Sean Owen
 */
public final class CaptureActivity extends BaseActivity implements SurfaceHolder.Callback {

    private static final String TAG = CaptureActivity.class.getSimpleName();
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;
    private RelativeLayout linearLayout;
    private SurfaceView scanPreview = null;
    private RelativeLayout scanContainer;
    private RelativeLayout scanCropView;
    private View scanLine;
    private boolean isTrue = true;
    private Rect mCropRect = null;
    private boolean isHasSurface = false;
    String userId = (String) SpUtils.get("module_user_id", "");

    public Handler getZxingHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    String taoTaskCardId;
    String taoTaskId;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_capture);
        scanPreview = findViewById(R.id.capture_preview);
        scanContainer = findViewById(R.id.capture_container);
        scanCropView = findViewById(R.id.capture_crop_view);
        scanLine = findViewById(R.id.capture_scan_line);
        linearLayout = findViewById(R.id.view_base_title_bar);
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.9f);
        animation.setDuration(4500);
        animation.setRepeatCount(-1);
        animation.setRepeatMode(Animation.RESTART);
        scanLine.startAnimation(animation);
        taoTaskCardId = getIntent().getStringExtra("taskCardId");
        taoTaskId = getIntent().getStringExtra("taskId");
        setBack();
        setTitleText("扫描");
    }

    @Override
    protected void onResume() {
        super.onResume();
        cameraManager = new CameraManager(getApplication());
        handler = null;
        if (isHasSurface) {
            initCamera(scanPreview.getHolder());
        } else {
            scanPreview.getHolder().addCallback(this);
        }
        inactivityTimer.onResume();
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        if (!isHasSurface) {
            scanPreview.getHolder().removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
        isTrue = false;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!isHasSurface) {
            isHasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isHasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    /**
     * A valid barcode has been found, so give an indication of success and show
     * the results.
     *
     * @param rawResult The contents of the barcode.
     * @param bundle    The extras
     */
    public void handleDecode(Result rawResult, Bundle bundle) {
        inactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();
        LogUtil.e("扫描获取到的值：" + rawResult.getText());
        if ("振航航空".equals(rawResult.getText().split("&")[0])) {
            ToastUtil.showToast("请扫描本APP生成专属二维码");
            return;
        }
        if (TextUtils.isEmpty(rawResult.getText())) {
            showInCommonDialog("扫描暂无结果请重试");
            return;
        }
        String pindanId = rawResult.getText().split("&")[0];
        String inviteCode = rawResult.getText().split("&")[1];
        getPindanDesc(pindanId,inviteCode);
    }

    Intent intentDelete;
    public void sentBroadcastDelete(String s) {
        if (intentDelete == null) {
            intentDelete = new Intent();
            intentDelete.setAction("moduleScan");
        }
        intentDelete.putExtra("pindanId", s);
        sendBroadcast(intentDelete);
        finish();
    }

    public void getPindanDesc(String pindanId, final String inviteCode) {
        HTTPAPI.getInstance().getPidanDesc(userId, pindanId, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("拼单详情获取成功" + s);
                sentBroadcastDelete(s + "&" + inviteCode);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("拼单详情获取失败" + e.getMessage());
            }
        });
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
            }
            initCrop();
        } catch (Exception e) {
            e.printStackTrace();
            displayFrameworkBugMessageAndExit();
        }
    }

    private void displayFrameworkBugMessageAndExit() {
        LogUtil.e("captureActivity方法打印==> displayFrameworkBugMessageAndExit  ");
    }

    public Rect getCropRect() {
        return mCropRect;
    }

    /**
     * 初始化截取的矩形区域
     */
    private void initCrop() {
        int cameraWidth = cameraManager.getCameraResolution().y;
        int cameraHeight = cameraManager.getCameraResolution().x;
        /** 获取布局中扫描框的位置信息 */
        int[] location = new int[2];
        scanCropView.getLocationInWindow(location);

        int cropLeft = location[0];
        int cropTop = location[1] - linearLayout.getHeight();

        int cropWidth = scanCropView.getWidth();
        int cropHeight = scanCropView.getHeight();

        /** 获取布局容器的宽高 */
        int containerWidth = scanContainer.getWidth();
        int containerHeight = scanContainer.getHeight();

        /** 计算最终截取的矩形的左上角顶点x坐标 */
        int x = cropLeft * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的左上角顶点y坐标 */
        int y = cropTop * cameraHeight / containerHeight;

        /** 计算最终截取的矩形的宽度 */
        int width = cropWidth * cameraWidth / containerWidth;
        /** 计算最终截取的矩形的高度 */
        int height = cropHeight * cameraHeight / containerHeight;

        /** 生成最终的截取的矩形 */
        mCropRect = new Rect(x, y, width + x, height + y);
    }

}